package com.example.blog.config;

/**
 * @ClassName: EnumConverter
 * @Description:

 * @Date 2024/1/27
 * @Version 1.0
 */
import com.example.blog.enums.CommentEnum;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class EnumConverter implements AttributeConverter<CommentEnum, String> {

    /**
     * 此方法告诉jpa数据库里存的值
     */
    @Override
    public String convertToDatabaseColumn(CommentEnum gradeEnum) {
        if (gradeEnum == null) {
            return null;
        }
        return gradeEnum.getCode();
    }

    /**
     * 此方法告诉Java从数据库里取出的值对应的是哪个enum值
     */
    @Override
    public CommentEnum convertToEntityAttribute(String des) {
        if (des == null) {
            return null;
        }
        for (CommentEnum gradeEnum : CommentEnum.values()) {
            if (gradeEnum.getCode().equals(des)) {
                return gradeEnum;
            }
        }
        throw new IllegalArgumentException(); // 或者给个默认的enum eg: return Category.UNKNOWN
    }
}

